export function showModal(title, placeholderText, editable, flag) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title,
      placeholderText,
      editable,
      confirmText: '确定',
      cancelText: '取消',
      success: function (r) {
        if (r.confirm) {
          // console.log('用户点击确定', r.content)
          if (flag === 1) {
            console.log('flag=1')
            if (!r.content.includes('1@') && !r.content.includes('0@')) {
              uni.showToast({ title: '输入格式不对' })
            } else resolve(r.content)
          } else if (flag === 2) {
            console.log('flag=1')
            if (!r.content) {
              uni.showToast({ title: '内容不能为空' })
            } else resolve(r.content)
          }
        } else if (r.cancel) {
          console.log('用户点击取消')
          uni.showToast({ title: '用户取消', duration: 1000 })
          reject('cancel')
        }
      },
    })
  })
}
export function modalShow(opts) {
  return new Promise((resolve, reject) => {
    const { title, placeholderText, editable, content } = opts
    uni.showModal({
      title,
      placeholderText,
      editable,
      content,
      confirmText: '确定',
      cancelText: '取消',
      success: function (r) {
        if (r.confirm) {
          // console.log('用户点击确定', r.content)
          resolve(r.content)
        } else if (r.cancel) {
          uni.showToast({ title: '用户取消', duration: 500 })
          reject('cancel')
        }
      },
    })
  })
}
//将字符数组转换成可读的数据
export function toValue(charList) {
  let unit = ''
  if (charList[5] === 'm') {
    unit = 'mm'
  } else if (charList[5] === 'i') unit = 'inch'
  return {
    value: parseFloat(charList.slice(6).join('')),
    unit: unit,
  }
}
export function dateShow() {
  //获取的时间是UTC对象，在获取小时等（getHours()）会自动转换成本地时间
  let d = new Date()
  let datetimeUTC = d.toJSON().substring(0, 19).replace('T', ' ')
  let datetime1 =
    [
      d.getFullYear(),
      (d.getMonth() + 1).toString().padStart(2, '0'),
      d.getDate().toString().padStart(2, '0'),
    ].join('-') +
    ' ' +
    [
      //getHours()获取的时间是本地时间
      d.getHours().toString().padStart(2, '0'),
      d.getMinutes().toString().padStart(2, '0'),
      d.getSeconds().toString().padStart(2, '0'),
    ].join(':')
  return [datetime1, datetimeUTC]
}
export const cmd = {
  //二进制bi数据转换成字符数组
  ab2char: (buffer) => {
    var charArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
      return '' + String.fromCharCode(bit)
    })
    // console.log('charArr: ', charArr)
    return charArr
  },
  //二进制bit数据转换成s十六进制数组
  ab2hex: (buffer) => {
    var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    })
    // console.log('ab2hex: ', hexArr)
    return hexArr
  },
  str2Hex: (str) => {
    let hex = ''
    for (let i = 0; i < str.length; i++) {
      // 获取字符的Unicode编码
      const charCode = str.charCodeAt(i)

      // 将编码转换为十六进制，并确保两位表示
      const hexValue = charCode.toString(16)

      // 拼接到结果字符串
      hex += hexValue.padStart(2, '0')
      //字符串十六进制数组
    }
    return hex
  },
  str2HexArr: (str) => {
    let hex = ''
    let arr = []
    for (let i = 0; i < str.length; i++) {
      // 获取字符的Unicode编码
      const charCode = str.charCodeAt(i)
      // 将编码转换为十六进制，并确保两位表示
      const hexValue = charCode.toString(16)
      // 拼接到结果字符串
      hex = hexValue.padStart(2, '0')
      //字符串十六进制数组
      arr.push(hex)
    }
    return arr
  },
  hex2Str: (hex) => {
    let str = ''
    for (let i = 0; i < hex.length; i += 2) {
      // 提取两个十六进制位
      const hexValue = hex.substr(i, 2)

      // 将十六进制转换为字符编码
      const charCode = parseInt(hexValue, 16)

      // 将字符编码转换为字符并拼接
      str += String.fromCharCode(charCode)
    }
    return str
  },
  // 格式化值 将16进制的数,低位放高位，设置指令时是：XL XH
  xhxl2xlxh: (n) => {
    let hex = n.length % 2 ? '0' + n : n
    return hex
      .split(/(.{2})/g)
      .filter((v) => v)
      .reverse()
  },
  // CRC-16/MODBUS 校验
  crc16modbus: (data) => {
    const dataBytes = data.map((v) => parseInt(v, 16))

    let crc = 0xffff
    const polynomial = 0xa001 // This is the polynomial x^16 + x^15 + x^2 + 1

    for (const byte of dataBytes) {
      crc ^= byte
      for (let i = 0; i < 8; i++) {
        if (crc & 0x0001) {
          crc = ((crc >> 1) ^ polynomial) & 0xffff
        } else {
          crc >>= 1
        }
      }
    }
    return crc.toString(16).toUpperCase().padStart(4, '0').match(/\w{2}/g).reverse()
  },
  //将指令的数组格式转换成buffer
  arrayToBuffer: (arr) => {
    let cmd = arr.map((v) => '0x' + v)
    // console.log("arrayToBuffer", cmd)
    let uint16arr = new Uint8Array(cmd)
    return uint16arr.buffer //返回由 Uint8Array引用的 ArrayBuffer
  },
}

export function onceEvent(eventName) {
  return new Promise((resolve, reject) => {
    uni.$once(eventName, (res) => {
      resolve(res)
    })
  })
}
